# coding: utf-8
# __author__ = 'fengzhao'

import sys
from flask import Flask, g, url_for
from flask_login import current_user, LoginManager
from celery import Celery
from . import config

reload(sys)
sys.setdefaultencoding("utf-8")


def create_app():
    app = Flask(__name__)
    app.config.from_object(config)

    @app.before_request
    def before_request():
        g.user = current_user

    register_db(app)
    register_jinja(app)
    return app


def register_db(app):
    from .models import db
    db.init_app(app)
    db.app = app
    with app.app_context():
        db.create_all()


def register_jinja(app):
    # Generate static resource url
    def static(filename):
        return url_for('static', filename=filename)

    app.jinja_env.globals['static'] = static


def make_celery(app):
    celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'])
    celery.conf.update(app.config)
    TaskBase = celery.Task

    class ContextTask(TaskBase):
        abstract = True

        def __call__(self, *args, **kwargs):
            with app.app_context():
                return TaskBase.__call__(self, *args, **kwargs)
    celery.Task = ContextTask
    return celery

app = create_app()
lm = LoginManager()
lm.init_app(app)
celery = make_celery(app)

# from controllers import XXX